package com.ljh.cloudmusic.utils;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.datatype.Artwork;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author: Themberfue
 * @date: 2025/3/8 16:14
 * @description:
 */
public class JaudiotaggerTest {
    public static void main(String[] args) {
        try {
            String musicFilePath = "D:/cloudmusic download/高梨康治 - 動天.flac";
            File file = new File(musicFilePath);
            AudioFile audioFile = AudioFileIO.read(file);
            Tag tag = audioFile.getTag();
            String outputImagePath = "E:/University Code Learning Journey/Java IDEA/JavaWebProject/Resources/CloudMusicResources/" +
                    tag.getFirst(FieldKey.TITLE) + "-" + tag.getFirst(FieldKey.ARTIST) + ".jpg";

            System.out.println("标题: " + tag.getFirst(FieldKey.TITLE));
            System.out.println("歌手: " + tag.getFirst(FieldKey.ARTIST));
            System.out.println("专辑: " + tag.getFirst(FieldKey.ALBUM));
            System.out.println("时长: " + audioFile.getAudioHeader().getTrackLength() + " 秒");
            // 获取封面
            Artwork artwork = tag.getFirstArtwork();
            if (artwork != null) {
                byte[] imageData = artwork.getBinaryData();
                // 直接写入文件
                try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
                    fos.write(imageData);
                    System.out.println("封面提取成功，已保存到：" + outputImagePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("未找到封面");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
